#!/usr/bin/env python
"""
导出Swagger文档到VitePress文档目录
"""
import os
import json
import subprocess
import sys
from pathlib import Path

# 获取项目根目录
BASE_DIR = Path(__file__).resolve().parent
DOCS_DIR = BASE_DIR.parent / 'mcphub-docs-vitepress' / 'docs' / 'api'

def export_swagger():
    """导出Swagger规范为JSON和YAML格式"""
    print("正在导出Swagger文档...")
    
    # 确保文档目录存在
    if not os.path.exists(DOCS_DIR):
        os.makedirs(DOCS_DIR)
    
    # 使用Django命令导出swagger.json
    swagger_json_path = DOCS_DIR / 'swagger.json'
    swagger_json_path_str = str(swagger_json_path).replace('\\', '/')
    subprocess.run([
        sys.executable, 'manage.py', 'shell', '-c',
        'from drf_yasg.utils import generate_swagger; from drf_yasg import openapi; '
        'from django.conf import settings; '
        'info = openapi.Info(title="MCPHUB API", default_version="v1", description="MCP协议Hub的API文档", '
        'terms_of_service="https://www.mcphub.org/terms/", '
        'contact=openapi.Contact(email="contact@mcphub.org"), '
        'license=openapi.License(name="MIT License")); '
        f'schema = generate_swagger(info); '
        f'with open("{swagger_json_path_str}", "w") as f: f.write(json.dumps(schema));'
    ], cwd=BASE_DIR)
    
    print(f"Swagger JSON 已导出到: {swagger_json_path}")
    
    # 创建VitePress集成文件
    create_vitepress_integration()
    
    print("文档导出完成！")

def create_vitepress_integration():
    """创建VitePress Swagger UI集成文件"""
    index_md_path = DOCS_DIR / 'swagger.md'
    
    index_content = """---
title: API 文档
description: MCPHUB API 文档
---

# MCPHUB API 文档

<ClientOnly>
  <SwaggerUI url="/api/swagger.json" />
</ClientOnly>
"""
    
    with open(index_md_path, 'w', encoding='utf-8') as f:
        f.write(index_content)
    
    print(f"已创建VitePress集成文件: {index_md_path}")

if __name__ == "__main__":
    export_swagger() 